/**
 * @description unlink menu
 * @author wangfupeng
 */

import { Transforms } from 'slate'
import { IButtonMenu, IDomEditor, DomEditor,SlateNode,SlateTransforms } from '@wangeditor/editor'
import { UN_LINK_SVG } from '../../icon-svg'
import { LinkCardElement } from '../../custom-types';


class UnLinkCard implements IButtonMenu {
  readonly title ='取消链接'
  readonly iconSvg = UN_LINK_SVG
  readonly tag = 'button'

  private getSelectedLinkElem(editor: IDomEditor): LinkCardElement | null {
    const node = DomEditor.getSelectedNodeByType(editor, 'link-card');
    if (node == null) return null;
    return node as LinkCardElement;
  }

  getValue(editor: IDomEditor): string | boolean {
    // 无需获取 val
    return ''
  }

  isActive(editor: IDomEditor): boolean {
    // 无需 active
    return false
  }

  isDisabled(editor: IDomEditor): boolean {
    if (editor.selection == null) return true

    const linkNode = DomEditor.getSelectedNodeByType(editor, 'link-card')
    if (linkNode == null) {
      // 选区未处于 link node ，则禁用
      return true
    }
    return false
  }

  exec(editor: IDomEditor, value: string | boolean) {
    if (this.isDisabled(editor)) return

    // 移除选中的结构，然后新增一个文本
    const linkElem = this.getSelectedLinkElem(editor);

    if (linkElem == null) return;

    const { title} = linkElem;
    const linkPath = DomEditor.findPath(editor, linkElem);
    SlateTransforms.removeNodes(editor, { at: linkPath });
    SlateTransforms.splitNodes(editor, { always: true });
    // 插入一个text
    Transforms.insertText(editor, title, { at: linkPath });
  }
}

export default UnLinkCard
